<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2019/1/2  10:11
 */
namespace app\driver\logic;
use app\driver\BaseModel;
use think\Cache;
use think\Db;
use app\driver\model\DriverWithdrawals as DriverWithdrawalsModel;
class Memberdriver extends  BaseModel
{

    //检测参数是否已传
    protected $ParameterDetection = [
        'editLicence' => ['idcard', 'drivercard'],
        'apply'=>['shopmobile'],
        'payment'=>['type'],
        'withdraw'=>['money'],
        'editDriver'=>['nickname','mobile','introduct','passwd']
    ];

    /*
    我的资料
    */
    public function driverInfo()
    {
        $uid = $this->user['id'];
        $sel = db('driver')->where(['id'=>$uid])->find();
        $sel['headimage'] = IMG_PATH.$sel['headimage'];
        unset($sel['passwd']);
        $result['driver_info']=$sel;
        return $result;
    }

    /*
     * 资料修改
     */
    public function editDriver()
    {
        $uid = $this->user['id'];
        $nickname = $this->requestData['nickname'];
        $mobile = $this->requestData['mobile'];
        $introduct = $this->requestData['introduct'];
        $withdraw_passwd = $this->requestData['passwd'];
        $driver = db('driver')->where(['id'=>$uid])->find();
        if(!$driver)return ['message'=>'数据不存在!'];
        if($nickname){$data['nickname'] = $nickname;}else{return ['message'=>'nickname参数必传'];}
        if($mobile){$data['mobile'] = $mobile;}else{return ['message'=>'mobile参数必传'];}
        if($introduct){$data['introduction'] = $introduct;}else{return ['message'=>'introduct参数必传'];}
        if($withdraw_passwd){$data['withdraw_passwd'] = md5($withdraw_passwd);}

        $file = request()->file('image');
        if($file){
            $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public/static/uploads');
            if ($info) {
                $image = $info->getSaveName();
                $data['headimage'] = $image;
            } else {
                return array('message'=>$file->getError());
            }
        }
        $sel = db('driver')->where(['id'=>$uid])->find();
        if(empty($sel) || isset($data)){
            if(!db('driver')->where(['id'=>$uid])->update($data))return ['message'=>'修改失败!'];
        }
        return array();
    }

    /*
     * 申请商家司机
     */
    public function  apply()
    {
        $uid = $this->user['id'];
        $shopmobile = $this->requestData['shopmobile'];
        $condition['driver_id'] = $uid;
        $condition['shop_mobile'] = $shopmobile;

        $res = db('driver_shop')->where($condition)->find();
        if($res)return ['message'=>'你已申请了该商家司机！'];
        $shop_id = db('shop')->where("mobile='".$shopmobile."'")->value('id');
        if(!$shop_id)return ['message'=>'店铺不存在！'];
        $data = [
            'driver_id'=>$uid,
            'shop_mobile'=>$shopmobile,
            'shop_id'=>$shop_id,
            'creatime'=>time()
        ];
        if(db('driver_shop')->insert($data))return array();
        return ['message'=>'申请失败！'];
    }

    /*
     * 我的商家
     */
    public function  myBusiness()
    {
        $uid = $this->user['id'];
//        die($uid);
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $limit=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $count = db('driver_shop')->where(['driver_id'=>$uid])->count();
        $where['ds.driver_id'] = $uid;
        $list  = db('driver_shop')->alias('ds')
            ->join('shop s','s.id = ds.shop_id','LEFT')
            ->field('ds.*,s.shopname,s.province,s.city,s.county,s.street,s.address,s.headimage,s.lng,s.lat')
            ->where($where)
            ->page($page,$limit)->select();
        foreach($list as $key=>&$value) {
            $value['headimage'] = IMG_PATH . $value['headimage'];
        }
        $result['list'] = $list;
        $result['count'] = $count;
        $result['page_num'] = $page;
        $result['page_limit'] = $limit;
        return $result;
    }

    /*
     *删除申请
     */
    public function unbind()
    {
        $uid = $this->user['id'];
        $id = $this->requestData['id'];
        if(!$id)return ['message'=>'参数必传!'];
        $condition['driver_id'] = $uid;
        $condition['id'] = $id;

        $res = db('driver_shop')->where($condition)->find();
        if(!$res)return ['message'=>'数据不存在！'];
        if($res['status'] == 1 && $res['isbind'] == 1)return ['message'=>'你无权删除该申请！'];

        if(db('driver_shop')->where(['id'=>$id])->delete())return array();
        return ['message'=>'删除该申请失败！'];
    }

    /*
     * 证件
     */
    public function licenceInfo()
    {
        $uid = $this->user['id'];
        $sel = db('driver')->where(['id'=>$uid])->field('id,idcard_number,driving_number,cart_number,driving_image')->find();
        $sel['driving_image'] = IMG_PATH_LICENSE.$sel['driving_image'];
        return $result['licence_info']=$sel;
    }

    /*
     * 编辑证件
     */
    public function editLicence()
    {
        $uid = $this->user['id'];
        $idcar = $this->requestData['idcard'];
        if(!$idcar)return ['message'=>'idcard不为空'];
        $licence = $this->requestData['drivercard'];
        if(!$licence)return ['message'=>'drivercard不为空'];
        $file = request()->file('image');
        $image = '';
        if (empty($file)){
            return array('message'=>'请上传图片');
        }else{
            $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public/static/certificates');
            if ($info) {
                $image = $info->getSaveName();
                $data['driving_image'] = $image;
            } else {
                return array('message'=>$file->getError());
            }
        }

        $data = [
            'driving_image'=>$image,
            'cart_number'=>$idcar,
            'driving_number'=>$licence,
            'status'=>0
        ];
        if(!db('driver')->where(['id'=>$uid])->update($data))return ['message'=>'修改失败!'];

        return array();
    }

    //我的钱包
    public function wallet()
    {
        $uid = $this->user['id'];
        $result = [];
        $user_balance = (new DriverWithdrawalsModel())->getUserBalance($uid);

        $result['user_balance'] = $user_balance;

        //是否绑定银行卡
        $member_bankcard = db('driver_bankcard')->where(['driver_id'=>$this->user['id']])->find();

        if(!empty($member_bankcard)){
            $result['is_binding'] = 1;          //绑定
        }else{
            $result['is_binding'] = 0;          //取消绑定
        }

        $result['bankcard_info'] = $member_bankcard;

        return $result;
    }

    //收支记录
    public function payment()
    {
        $uid = $this->user['id'];
        $type = $this->requestData['type'];
        $page=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $limit=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        switch($type){
            case '1':
                //收入
                $list = db('driver_balance')->where(['driver_id'=>$uid])->order('id desc')->page($page,$limit)->select();
                $count = db('driver_balance')->where(['driver_id'=>$uid])->count();
                break;
            default:
                //支出
                $list = db('driver_withdrawals')->where(['driver_id'=>$uid])->order('id desc')->page($page,$limit)->select();
                $count = db('driver_withdrawals')->where(['driver_id'=>$uid])->count();
        }
        $result['list'] = $list;
        $data['count'] = $count;
        $data['page_num']=$page;
        $data['page_limit']=$limit;
        return $result;
    }

    public function paymentInfo()
    {
        $uid = $this->user['id'];
        $id = $this->requestData['id'];
        $type = $this->requestData['type'];
        switch($type){
            case '1':
                //收入
                $list = db('driver_balance')->where(['driver_id'=>$uid,'id'=>$id])->find();
                $list['create_time'] = date("Y-m-d H:i:s",$list['create_time']);
                if(!$list)return ['message'=>'数据异常!'];
                break;
            default:
                //支出
                $list = db('driver_withdrawals')->where(['driver_id'=>$uid,'id'=>$id])->find();
                $list['create_time'] = date("Y-m-d H:i:s",$list['create_time']);
                $list['check_time'] = date("Y-m-d H:i:s",$list['check_time']);
                if(!$list)return ['message'=>'数据异常!'];
        }
        $result['info'] = $list;
        return $result;
    }

    //提现
    public function withdraw(){
        (new \app\api\validate\System())->apply();

        $db_withdrawals = db("driver_withdrawals");

        $user_balance = (new DriverWithdrawalsModel())->getUserBalance($this->user['id']);

        $config=db("config")->where("id=5")->find();
        $poundage=round(floatval($config['value'])*$this->requestData['money']/100,2);

        $db_bankcard = db("driver_bankcard");
        $card=$db_bankcard->where(['driver_id'=>$this->user['id']])->find();
        $code = isset($this->requestData['code'])?$this->requestData['code']:'';
        $mdcode = md5(trim($code));
        if(empty($code))return ['message'=>'提现密码为空!'];
        $withdraw_passwd = db('driver')->where(['id'=>$this->user['id']])->value('withdraw_passwd');
        if ($mdcode != $withdraw_passwd) {
            return array('message'=>'提现密码错误');
        }

        if(floatval($this->requestData['money'])<=0) return array("message"=>'提现金额有误');
        if($user_balance<floatval($this->requestData['money'])) return array("message"=>'余额不足');
        if(empty($card))return array("message"=>'请填写银行卡信息才能提现!');

        $data = [
            'driver_id' => $this->user['id'],
            'money' =>$this->requestData['money'],
            'poundage' =>$poundage,
            'paid' => $this->requestData['money']-$poundage,
            'create_time' =>TIMESTAMP,
            "name"=> $card['name'],
            "card_num"=>$card['card_num'],
            "mobile"=>$card['mobile'],
            "bank"=>$card['bank']
        ];
        try{
            $res=$db_withdrawals->insert($data);
            if(!$res) throw new \Exception('提现失败');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array("message"=>$e->getMessage());
        }
    }

}


